package com.lbb.springboot.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;

/**
 * Created by hgg on 2018/2/24.
 * 小程序AES解密
 */
public class AESDecodeUtils {

    public static void main(String[] args) throws Exception {
        byte[] encrypData = Base64.decodeBase64("yUCj5LfDn38W0n+G6GDG9ivl3xONDRgAQgZbh+w2Jltta+rg5oLq6iLcV+gckded5ISf4qTeS1mGGKcTg7wU+3rCSHXM0mehb0fsa1jHNYWXbao/xY/P5TycNPEhxu3/yn9XuquMJhJF/iXnz4aS9KLKV1sC5MWcW7668g7GetnMd1giqilQMIcm7jMkecLXLNOB6XArJqx9lYSHjeS34g==");
        byte[] ivData = Base64.decodeBase64("lsXkTP94PoFSzXCSQ3xUCg==");
        byte[] sessionKey = Base64.decodeBase64("dUrei+foSG9JysGWbsBzxQ==");

        System.out.println(decrypt(sessionKey, ivData, encrypData));
    }


    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

        String base64Str = java.util.Base64.getEncoder().encodeToString(cipher.doFinal(encData));
        //解析解密后的字符串
        return new String(cipher.doFinal(encData), "UTF-8");
    }


}